package java2_chatroom;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端读取服务器发来信息线程
 */
class ReadFromServer implements Runnable {
    private Socket client;

    public ReadFromServer(Socket client) {
        this.client = client;
    }
    @Override
    public void run() {
        try {
            // 获取客户端输入流，读取服务器发来的信息
            Scanner in = new Scanner(client.getInputStream());
            while (true) {
                if (in.hasNextLine()) {
                    System.out.println("从服务器发来的信息为: "+in.nextLine());
                }
                // 读线程关闭标志
                if (client.isClosed()) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 向服务器发送信息线程
 */
class WriteToServer implements Runnable {
    private Socket client;

    public WriteToServer(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            // 获取键盘输入流，读取用户从键盘发来的信息
            Scanner scanner = new Scanner(System.in);
            String string = "";
            // 获取客户端输出流，将用户键入的信息发送给服务器
            PrintStream out = new PrintStream(client.getOutputStream(),
                    true,"UTF-8");
            while (true) {
                System.out.println("请输入向服务器发送的信息...");
                if (scanner.hasNextLine()) {
                    string = scanner.nextLine();
                    out.println(string);
                }
                // 设置退出标志
                if (string.contains("byebye")) {
                    System.out.println("客户端退出，不聊了!");
                    scanner.close();
                    out.close();
                    client.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 多线程版本客户端实现
 * @author yuisama
 * @date 2018/8/31 19:52
 */
public class MultiThreadClient {
    public static void main(String[] args) {
        try {
            Socket client = new Socket("127.0.0.1",6666);
            Thread readThread = new Thread(new ReadFromServer(client));
            Thread writeThread = new Thread(new WriteToServer(client));
            readThread.start();
            writeThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
